<?php
/**
 * Created by PhpStorm.
 * User: 郑好
 * Date: 2019/7/1
 * Time: 上午9:43
 */

namespace app\common;

class EasyNumTool
{
    use InstanceTrait;

    /**
     * @param       $num
     * @return      bool
     * @description 是否奇数
     */
    public function isOdd($num)
    {
        $num = (int)$num;
        return ($num%2==0)?false:true;
    }

    /**
     * @param       $num
     * @return      bool
     * @description 是否偶数
     */
    public function isEven($num)
    {
        $num = (int)$num;
        return ($num%2==0)?true:false;
    }

    /**
     * @param       $array
     * @param       string $delimiter
     * @return      string
     * @description 奇偶比
     */
    public function oddEvenRatio($array, $delimiter = ":")
    {
        $oddNum = 0;
        $evenNum = 0;
        foreach ($array as $item) {
            ($this->isOdd($item))?$oddNum++:$evenNum++;
        }
        return $oddNum . $delimiter . $evenNum;
    }

    /**
     * @param       $num
     * @return      bool
     * @description 是否质数
     */
    public function isPrime($num)
    {
        if ($num === 0) {
            return false;
        } elseif ($num <= 3) {
            return true;
            //            return $num > 1;
        } elseif ($num % 2 === 0 || $num % 3 === 0) { // 排除能被2整除的数(2x)和被3整除的数(3x)
            return false;
        } else { // 排除能被6x+1和6x+5整除的数
            for ($i = 5; $i * $i <= $num; $i += 6) {
                if ($num % $i === 0 || $num % ($i + 2) === 0) {
                    return false;
                }
            }
            return true;
        }
    }

    /**
     * @param       $num
     * @return      bool
     * @description 是否合数
     */
    public function isComposite($num)
    {
        return ($this->isPrime($num))?false:true;
    }


    /**
     * @param       $array
     * @param       string $delimiter
     * @return      string
     * @description 质合比
     */
    public function primeCompositeRatio($array, $delimiter = ":")
    {
        $primeNum = 0;
        $compositeNum = 0;
        foreach ($array as $item) {
            ($this->isPrime($item))?$primeNum++:$compositeNum++;
        }
        return $primeNum . $delimiter . $compositeNum;
    }
}
